<template>
  <div class="portfolio-management">
    <h3>投资组合管理</h3>
    
    <!-- 操作按钮区域 -->
    <div class="portfolio-actions">
      <button class="btn btn-primary" @click="showAddDialog = true">添加持仓</button>
      <button class="btn btn-secondary" @click="refreshPortfolio">刷新数据</button>
      <button class="btn btn-secondary" @click="exportPortfolio">导出组合</button>
    </div>
    <div class="portfolio-overview">
      <div class="overview-card">
        <div class="card-title">总市值</div>
        <div class="card-value">{{ formatCurrency(portfolio.totalValue) }}</div>
        <div class="card-change" :class="portfolio.totalChangePercent >= 0 ? 'up' : 'down'">
          {{ portfolio.totalChangePercent >= 0 ? '+' : '' }}{{ portfolio.totalChangePercent }}%
          ({{ portfolio.totalChange >= 0 ? '+' : '' }}{{ formatCurrency(portfolio.totalChange) }})
        </div>
      </div>
      <div class="overview-card">
        <div class="card-title">日收益</div>
        <div class="card-value">{{ formatCurrency(portfolio.dailyProfit) }}</div>
        <div class="card-change" :class="portfolio.dailyProfitPercent >= 0 ? 'up' : 'down'">
          {{ portfolio.dailyProfitPercent >= 0 ? '+' : '' }}{{ portfolio.dailyProfitPercent }}%
        </div>
      </div>
      <div class="overview-card">
        <div class="card-title">持有股票</div>
        <div class="card-value">{{ portfolio.holdings.length }}只</div>
        <div class="card-change">
          现金占比: {{ portfolio.cashPercent }}%
        </div>
      </div>
    </div>
    
    <div class="portfolio-holdings">
      <div class="section-header">
        <h4>持仓明细</h4>
        <div class="search-container">
          <input 
            type="text" 
            v-model="searchQuery" 
            placeholder="搜索股票代码或名称" 
            class="search-input"
          />
        </div>
      </div>
      <div class="holdings-table">
        <div class="table-header">
          <div class="table-cell">股票名称</div>
          <div class="table-cell">代码</div>
          <div class="table-cell">持仓数量</div>
          <div class="table-cell">成本价</div>
          <div class="table-cell">现价</div>
          <div class="table-cell">市值</div>
          <div class="table-cell">盈亏额</div>
          <div class="table-cell">盈亏率</div>
          <div class="table-cell">操作</div>
        </div>
        <div class="table-row" v-for="(stock, index) in filteredHoldings" :key="index">
          <div class="table-cell">{{ stock.name }}</div>
          <div class="table-cell">{{ stock.code }}</div>
          <div class="table-cell">{{ stock.quantity }}</div>
          <div class="table-cell">{{ formatCurrency(stock.costPrice) }}</div>
          <div class="table-cell">{{ formatCurrency(stock.currentPrice) }}</div>
          <div class="table-cell">{{ formatCurrency(stock.marketValue) }}</div>
          <div class="table-cell" :class="stock.profit >= 0 ? 'profit' : 'loss'">
            {{ stock.profit >= 0 ? '+' : '' }}{{ formatCurrency(stock.profit) }}
          </div>
          <div class="table-cell" :class="stock.profitRate >= 0 ? 'profit' : 'loss'">
            {{ stock.profitRate >= 0 ? '+' : '' }}{{ stock.profitRate.toFixed(2) }}%
          </div>
          <div class="table-cell">
            <button class="btn btn-small btn-edit" @click="editHolding(stock)">编辑</button>
            <button class="btn btn-small btn-delete" @click="deleteHolding(index)">删除</button>
          </div>
        </div>
      </div>
    </div>
    
    <div class="portfolio-allocation">
      <h4>资产配置</h4>
      <div class="allocation-chart">
        <div class="allocation-item" v-for="(item, index) in portfolio.allocation" :key="index">
          <div class="allocation-color" :style="{ backgroundColor: item.color }"></div>
          <div class="allocation-info">
            <div class="allocation-name">{{ item.name }}</div>
            <div class="allocation-percent">{{ item.percent }}%</div>
          </div>
        </div>
      </div>
    </div>
  </div>
  
  <!-- 添加/编辑持仓对话框 -->
  <div v-if="showAddDialog || showEditDialog" class="modal-overlay" @click.self="closeDialog">
    <div class="modal-container">
      <div class="modal-header">
        <h4>{{ showEditDialog ? '编辑持仓' : '添加持仓' }}</h4>
        <button class="close-btn" @click="closeDialog">&times;</button>
      </div>
      <div class="modal-body">
        <div class="form-group">
          <label>股票代码</label>
          <input 
            type="text" 
            v-model="formData.code" 
            :disabled="showEditDialog"
            class="form-input"
          />
        </div>
        <div class="form-group">
          <label>股票名称</label>
          <input 
            type="text" 
            v-model="formData.name" 
            class="form-input"
          />
        </div>
        <div class="form-group">
          <label>持仓数量</label>
          <input 
            type="number" 
            v-model.number="formData.quantity" 
            min="1"
            class="form-input"
          />
        </div>
        <div class="form-group">
          <label>成本价</label>
          <input 
            type="number" 
            v-model.number="formData.costPrice" 
            min="0.01"
            step="0.01"
            class="form-input"
          />
        </div>
      </div>
      <div class="modal-footer">
        <button class="btn btn-secondary" @click="closeDialog">取消</button>
        <button class="btn btn-primary" @click="saveHolding">{{ showEditDialog ? '更新' : '添加' }}</button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';

interface StockHolding {
  name: string;
  code: string;
  quantity: number;
  costPrice: number;
  currentPrice: number;
  marketValue: number;
  profit: number;
  profitRate: number;
}

interface PortfolioAllocation {
  name: string;
  percent: number;
  color: string;
}

interface PortfolioData {
  totalValue: number;
  totalChange: number;
  totalChangePercent: number;
  dailyProfit: number;
  dailyProfitPercent: number;
  cashPercent: number;
  holdings: StockHolding[];
  allocation: PortfolioAllocation[];
}

interface FormData {
  code: string;
  name: string;
  quantity: number;
  costPrice: number;
}

// 交互状态
const searchQuery = ref('');
const showAddDialog = ref(false);
const showEditDialog = ref(false);
const currentEditIndex = ref(-1);
const formData = ref<FormData>({
  code: '',
  name: '',
  quantity: 0,
  costPrice: 0
});

const portfolio = ref<PortfolioData>({
  totalValue: 158724.50,
  totalChange: 4582.30,
  totalChangePercent: 3.0,
  dailyProfit: 1258.75,
  dailyProfitPercent: 0.8,
  cashPercent: 25.5,
  holdings: [
    {
      name: '腾讯控股',
      code: '00700',
      quantity: 100,
      costPrice: 320.50,
      currentPrice: 342.80,
      marketValue: 34280.00,
      profit: 2230.00,
      profitRate: 7.0
    },
    {
      name: '贵州茅台',
      code: '600519',
      quantity: 10,
      costPrice: 1850.00,
      currentPrice: 1980.00,
      marketValue: 19800.00,
      profit: 1300.00,
      profitRate: 7.0
    },
    {
      name: '阿里巴巴',
      code: '09988',
      quantity: 200,
      costPrice: 85.60,
      currentPrice: 82.30,
      marketValue: 16460.00,
      profit: -660.00,
      profitRate: -3.8
    },
    {
      name: '宁德时代',
      code: '300750',
      quantity: 50,
      costPrice: 180.00,
      currentPrice: 195.60,
      marketValue: 9780.00,
      profit: 780.00,
      profitRate: 8.7
    },
    {
      name: '招商银行',
      code: '600036',
      quantity: 300,
      costPrice: 35.80,
      currentPrice: 37.20,
      marketValue: 11160.00,
      profit: 420.00,
      profitRate: 3.9
    }
  ],
  allocation: [
    { name: '科技股', percent: 45.5, color: '#3498db' },
    { name: '消费股', percent: 18.0, color: '#e74c3c' },
    { name: '金融股', percent: 11.0, color: '#2ecc71' },
    { name: '新能源', percent: 25.5, color: '#f39c12' }
  ]
});

// 过滤后的持仓列表
const filteredHoldings = computed(() => {
  if (!searchQuery.value) return portfolio.value.holdings;
  
  const query = searchQuery.value.toLowerCase();
  return portfolio.value.holdings.filter(stock => 
    stock.code.toLowerCase().includes(query) || 
    stock.name.toLowerCase().includes(query)
  );
});

// 格式化货币
const formatCurrency = (value: number) => {
  return '¥' + value.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
};

// 刷新投资组合数据
const refreshPortfolio = () => {
  // 模拟刷新操作
  console.log('刷新投资组合数据');
  
  // 随机更新股票价格
  portfolio.value.holdings.forEach(stock => {
    const changeFactor = 0.98 + Math.random() * 0.04; // 98% 到 102% 之间的随机变化
    stock.currentPrice = Number((stock.currentPrice * changeFactor).toFixed(2));
    stock.marketValue = Number((stock.currentPrice * stock.quantity).toFixed(2));
    stock.profit = Number((stock.marketValue - stock.costPrice * stock.quantity).toFixed(2));
    stock.profitRate = Number((stock.profit / (stock.costPrice * stock.quantity) * 100).toFixed(2));
  });
  
  // 更新总市值和变化
  updatePortfolioSummary();
};

// 更新投资组合汇总数据
const updatePortfolioSummary = () => {
  const totalValue = portfolio.value.holdings.reduce((sum, stock) => sum + stock.marketValue, 0);
  const previousValue = totalValue - portfolio.value.totalChange;
  
  portfolio.value.totalValue = Number(totalValue.toFixed(2));
  portfolio.value.totalChange = Number((totalValue - previousValue * 0.97).toFixed(2)); // 模拟基准变化
  portfolio.value.totalChangePercent = Number((portfolio.value.totalChange / previousValue * 100).toFixed(2));
};

// 编辑持仓
const editHolding = (stock: StockHolding) => {
  const index = portfolio.value.holdings.findIndex(s => s.code === stock.code);
  if (index !== -1) {
    currentEditIndex.value = index;
    formData.value = {
      code: stock.code,
      name: stock.name,
      quantity: stock.quantity,
      costPrice: stock.costPrice
    };
    showEditDialog.value = true;
    showAddDialog.value = false;
  }
};

// 删除持仓
const deleteHolding = (index: number) => {
  if (confirm('确定要删除这个持仓吗？')) {
    portfolio.value.holdings.splice(index, 1);
    updatePortfolioSummary();
  }
};

// 保存持仓
const saveHolding = () => {
  // 验证表单
  if (!formData.value.code || !formData.value.name || formData.value.quantity <= 0 || formData.value.costPrice <= 0) {
    alert('请填写完整的持仓信息');
    return;
  }
  
  // 模拟当前价格（基于成本价上下浮动5%）
  if (!formData.value.code || !formData.value.name || formData.value.quantity <= 0 || formData.value.costPrice <= 0) {
    alert('请填写完整的股票信息且数量和价格必须大于0');
    return;
  }
  
  const basePrice = formData.value.costPrice;
  const currentPrice = Number((basePrice * (0.95 + Math.random() * 0.1)).toFixed(2));
  const marketValue = Number((currentPrice * formData.value.quantity).toFixed(2));
  const profit = Number((marketValue - basePrice * formData.value.quantity).toFixed(2));
  const profitRate = Number((profit / (basePrice * formData.value.quantity) * 100).toFixed(2));
  
  if (showEditDialog.value && currentEditIndex.value !== -1 && currentEditIndex.value < portfolio.value.holdings.length) {
    // 更新现有持仓
    const stock = portfolio.value.holdings[currentEditIndex.value];
    if (stock) {
      if (formData.value) {
        stock.name = formData.value.name || '';
        stock.quantity = formData.value.quantity || 0;
        stock.costPrice = formData.value.costPrice || 0;
      }
      stock.currentPrice = currentPrice;
      stock.marketValue = marketValue;
      stock.profit = profit;
      stock.profitRate = profitRate;
    }
  } else {
    // 检查是否已存在该股票
    const exists = portfolio.value.holdings.some(stock => stock.code === formData.value.code);
    if (exists) {
      alert('该股票代码已存在，请使用编辑功能或更换股票代码');
      return;
    }
    
    // 添加新持仓
    portfolio.value.holdings.push({
      code: formData.value.code,
      name: formData.value.name,
      quantity: formData.value.quantity,
      costPrice: formData.value.costPrice,
      currentPrice: currentPrice,
      marketValue: marketValue,
      profit: profit,
      profitRate: profitRate
    });
  }
  
  updatePortfolioSummary();
  closeDialog();
};

// 关闭对话框
const closeDialog = () => {
  showAddDialog.value = false;
  showEditDialog.value = false;
  currentEditIndex.value = -1;
  // 重置表单
  formData.value = {
    code: '',
    name: '',
    quantity: 0,
    costPrice: 0
  };
};

// 导出投资组合
const exportPortfolio = () => {
  // 模拟导出功能
  alert('正在导出投资组合数据...');
  console.log('导出投资组合:', portfolio.value);
};
</script>

<style scoped>
.portfolio-management {
  background: white;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

h3 {
  margin: 0 0 20px 0;
  color: #2c3e50;
  font-size: 18px;
}

/* 操作按钮 */
.portfolio-actions {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s;
}

.btn-primary {
  background-color: #3498db;
  color: white;
}

.btn-primary:hover {
  background-color: #2980b9;
}

.btn-secondary {
  background-color: #ecf0f1;
  color: #2c3e50;
  border: 1px solid #bdc3c7;
}

.btn-secondary:hover {
  background-color: #bdc3c7;
}

.btn-small {
  padding: 4px 10px;
  font-size: 12px;
  margin-right: 5px;
}

.btn-edit {
  background-color: #3498db;
  color: white;
}

.btn-delete {
  background-color: #e74c3c;
  color: white;
}

/* 搜索区域 */
.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.search-container {
  width: 250px;
}

.search-input {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #bdc3c7;
  border-radius: 4px;
  font-size: 14px;
}

.search-input:focus {
  outline: none;
  border-color: #3498db;
}

/* 表格调整 */
.table-header {
  grid-template-columns: 2fr 1fr 1fr 1fr 1fr 1fr 1fr 1fr 1fr;
}
.table-row {
    grid-template-columns: 2fr 1fr 1fr 1fr 1fr 1fr 1fr 1fr 1fr;
  }

h4 {
  margin: 20px 0 12px 0;
  color: #34495e;
  font-size: 16px;
}

.portfolio-overview {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 16px;
  margin-bottom: 20px;
}

.overview-card {
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  border-radius: 8px;
  padding: 16px;
  text-align: center;
}

.card-title {
  font-size: 14px;
  color: #7f8c8d;
  margin-bottom: 8px;
}

.card-value {
  font-size: 24px;
  font-weight: bold;
  color: #2c3e50;
  margin-bottom: 4px;
}

.card-change {
  font-size: 14px;
}

.card-change.up {
  color: #e74c3c;
}

.card-change.down {
  color: #2ecc71;
}

.portfolio-holdings {
  margin-bottom: 20px;
}

.holdings-table {
  border: 1px solid #e0e0e0;
  border-radius: 6px;
  overflow: hidden;
}

.table-header {
  display: grid;
  grid-template-columns: 2fr 1fr 1fr 1fr 1fr 1fr 1fr 1fr;
  background-color: #f8f9fa;
  padding: 12px;
  font-weight: 600;
  color: #34495e;
  font-size: 14px;
}

.table-row {
  display: grid;
  grid-template-columns: 2fr 1fr 1fr 1fr 1fr 1fr 1fr 1fr;
  padding: 12px;
  border-top: 1px solid #e0e0e0;
  font-size: 14px;
  color: #2c3e50;
}

.table-row:hover {
  background-color: #f8f9fa;
}

.table-cell {
  display: flex;
  align-items: center;
}

.profit {
  color: #e74c3c;
}

.loss {
  color: #2ecc71;
}

.portfolio-allocation {
  margin-top: 20px;
}

.allocation-chart {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.allocation-item {
  display: flex;
  align-items: center;
  gap: 12px;
}

.allocation-color {
  width: 20px;
  height: 20px;
  border-radius: 4px;
}

.allocation-info {
  display: flex;
  justify-content: space-between;
  flex: 1;
}

.allocation-name {
  color: #34495e;
}

.allocation-percent {
  font-weight: 500;
  color: #2c3e50;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-container {
  background: white;
  border-radius: 8px;
  width: 90%;
  max-width: 500px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #e0e0e0;
}

.modal-header h4 {
  margin: 0;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #7f8c8d;
  padding: 0;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.modal-body {
  padding: 20px;
}

.form-group {
  margin-bottom: 16px;
}

.form-group label {
  display: block;
  margin-bottom: 6px;
  font-weight: 500;
  color: #2c3e50;
}

.form-input {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #bdc3c7;
  border-radius: 4px;
  font-size: 14px;
}

.form-input:focus {
  outline: none;
  border-color: #3498db;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding: 16px 20px;
  border-top: 1px solid #e0e0e0;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .portfolio-overview {
    grid-template-columns: 1fr;
  }
  
  .portfolio-actions {
    flex-wrap: wrap;
  }
  
  .section-header {
    flex-direction: column;
    align-items: stretch;
    gap: 10px;
  }
  
  .search-container {
    width: 100%;
  }
  
  .table-header,
  .table-row {
    grid-template-columns: 1fr 1fr;
  }
  
  .modal-container {
    width: 95%;
    margin: 20px;
  }
}
</style>